package com.codebyorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codebyorder.entity.Category;
import com.codebyorder.mapper.CategoryMapper;
import com.codebyorder.req.CategoryQueryReq;
import com.codebyorder.req.CategorySaveReq;
import com.codebyorder.resp.CommonResp;
import com.codebyorder.resp.CategoryQueryResp;
import com.codebyorder.resp.PageResp;
import com.codebyorder.service.CategoryService;
import com.codebyorder.util.CopyUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private CategoryService categoryService;

    @GetMapping("/list")
    public CommonResp<PageResp<CategoryQueryResp>> list(@Valid CategoryQueryReq categoryQueryReq) {
        CommonResp<PageResp<CategoryQueryResp>> resp = new CommonResp<>();
        resp.setContent(categoryService.categoryToResp(categoryQueryReq));
        return resp;
    }

    @GetMapping("/all")
    public List<CategoryQueryResp> all() {
        QueryWrapper<Category> queryWrap=new QueryWrapper<>();
        queryWrap.orderByAsc("sort");
        List<Category> categorys = categoryMapper.selectList(queryWrap);
        return CopyUtil.copyList(categorys, CategoryQueryResp.class);
    }

    @PostMapping("/save")
    public CommonResp<Object> save(@Valid @RequestBody CategorySaveReq categorySaveReq) {
        Category category = CopyUtil.copy(categorySaveReq, Category.class);
        if (category.getId() == null) {
            categoryMapper.insert(category);
        } else {
            categoryMapper.updateById(category);
        }
        return new CommonResp<>();
    }

    @DeleteMapping("/delete/{id}")
    public CommonResp<Object> delete(@PathVariable Long id) {
        categoryMapper.deleteById(id);
        return new CommonResp<>();
    }

}
